<?php
	class Sss_Ultility_InventoryFuction {
		/**
		* Get relate of stock location for (document, shipment...)
		* @param array $row list stocklocation
		* return array
		*/
		function getRelateStockLocation($row)
		{
			$listInventory    = array();
			$listDocument    = array();
			$listShipment    = array();
			$listInstance    = array();
			$listCompnayOwner    = array();
			$inventoryTable = new Application_Model_Mapper_Inventory();
			$documentTable = new Application_Model_Mapper_Document();
			$instanceTable = new Application_Model_Mapper_Instance();
			$stocklocationsTable = new Application_Model_Mapper_StockLocation();
			$accountTable = new Application_Model_Mapper_Account();
			foreach ((array) $row as $r) {
				//get inventory by stock location
				$inventory           = $inventoryTable->getInventoryByStockLocation($r['stocklocationid']);
				$listInventory[] = $inventory != false ? count($inventory) : 0;
				//get SLA by stock location
				$document           = $documentTable->getDocumentByStocklocationId($r['stocklocationid'], Sss_Ultility_Setting::DOCUMENT_SLA);
				$listDocument[] = $document != false ? count($document) : 0;
				//get instances by stock location
				$instance = $instanceTable->getInstanceByStock($r['stocklocationid']);
				$listInstance[] = $instance != false ? count($instance) : 0;
				//get instances by stock location
				$instances = $instanceTable->getList();
				$isNull = false;
				$i = 0;
				$countInstance = count($instances);
				foreach($instances as $ins) {
					$i = $i + 1;
					//get shipment by stock location
					$shipment           = $stocklocationsTable->getShipmentByStockLocation($r['stocklocationid'], $ins['instanceid']);
					if($shipment != false && $isNull == false){
						$isNull = true;
						$listShipment[] = count($shipment);
					} else if($isNull == false && $i == $countInstance){
							$listShipment[] = 0;
						}
				}
				//get company owner account name by stock location
				$compnayOwner           = $accountTable->getCompanyOwnerByStockLocation($r['stocklocationid']);
				$compnayOwnerName = '';
				if(count($compnayOwner) > 0) {
					foreach($compnayOwner as $c){
						if($compnayOwnerName != ''){
							$compnayOwnerName = $compnayOwnerName.', ';
						}
						$compnayOwnerName = $compnayOwnerName.$c['fullname'];
					}
					$listCompnayOwner[] = $compnayOwnerName;
				} else {
					$listCompnayOwner[] = $compnayOwnerName;
				}
			}	
			$arrRelateStockLocation = array();
			$arrRelateStockLocation[Sss_Ultility_CommonViewParamater::SHIPMENT] = $listShipment;
			$arrRelateStockLocation[Sss_Ultility_CommonViewParamater::INVENTORY] = $listInventory;
			$arrRelateStockLocation[Sss_Ultility_CommonViewParamater::DOCUMENT] = $listDocument;
			$arrRelateStockLocation[Sss_Ultility_CommonViewParamater::INSTANCE] = $listInstance;
			$arrRelateStockLocation[Sss_Ultility_CommonViewParamater::ACCOUNT] = $listCompnayOwner;
			return $arrRelateStockLocation;
		}
		/**
		* @param int $stockLocationtId
		* return boolean
		*/
		function invisibleOrVisibleStock($stockLocationtId)
		{
			$stocklocationsTable = new Application_Model_Mapper_StockLocation();
			$stockLocationInstanceTable = new Application_Model_Mapper_StockLocationInstance();
			$instanceTable = new Application_Model_Mapper_Instance();
			$stockLocation = $stocklocationsTable->findById((int) $stockLocationtId);
			//update isarchived
			$isarchived =$stockLocation->isarchived == 1? 0 : 1;
			$stockGatewave = $stocklocationsTable->findById($stockLocationtId);
			$stockGatewave->setIsarchived($isarchived);
			$visibleId = $stocklocationsTable->save($stockGatewave);
			//End update
			if (isset($visibleId)) {
				$instance = $stockLocationInstanceTable->getInstanceByStockLocationId($stockLocationtId);
				$instanceId = $instance->instance ;
				$deleteStockLocationId = array('stocklocation = ?' => $stockLocationtId);
				$deleteStockId = $stockLocationInstanceTable->deleteRow( null , $deleteStockLocationId);
				if($deleteStockId){
					if($instanceId){
						$stockLocationCurrent = $stockLocationInstanceTable->getStockLocationByInstance($instanceId);
						if($stockLocationCurrent){
							$stockLocationDefault = $stockLocationCurrent[0]['stocklocation'];
							$instanceGatewave = $instanceTable->findById((int)$instanceId);
							$instanceGatewave->setStockLocation($stockLocationDefault);
							$instanceTable->save($instanceGatewave);
						}
					}
				}
				return true;
			} else {
				return false;
			}
		}
		/**
		* @param int $stockLocationtId
		* return boolean
		*/
		function deleteStockLocation($stockLocationtId, $instanceId)
		{
			$inventoryTable = new Application_Model_Mapper_Inventory();
			$documentTable = new Application_Model_Mapper_Document();
			$instanceTable = new Application_Model_Mapper_Instance();
			$stocklocationsTable = new Application_Model_Mapper_StockLocation();
			$inventory           = $inventoryTable->getInventoryByStockLocation($stockLocationtId);
			$document           = $documentTable->getDocumentByStocklocationId($stockLocationtId, Sss_Ultility_Setting::DOCUMENT_SLA);
			$instance = $instanceTable->getInstanceByStockLocation($stockLocationtId);
			//get instances by stock location
			$instances = $instanceTable->getList();
			$isNull = false;
			foreach($instances as $ins){
				//get shipment by stock location
				$shipment           = $stocklocationsTable->getShipmentByStockLocation($stockLocationtId, $ins['instanceid']);
				if($shipment != false && $isNull == false){
					$isNull = true;
				}
			}
			if($inventory == false && $document == false && $instance == false && $isNull == false){
				$deleteId = $stocklocationsTable->deleteRow($stockLocationtId, null, $instanceId);
				if (isset($deleteId)) {
					return true;
				} else {
					return false;
				}
			}else{
				return false;
			}
		}

		/**
		* @param int $stockLocationtId,$stockLocation....
		* return boolean
		*/
		function editStockLocation($stockLocationId,$stockLocation,$data,$paramOwner)
		{
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$StockLocationCompanyOwnerTable = new Application_Model_Mapper_StockLocationCompanyOwner();
			$instanceTable = new Application_Model_Mapper_Instance();
			$accountTable = new Application_Model_Mapper_Account();
			//upload stock location photo
			$fullPath = null;
			$fileName = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::NAME];
			if ($fileName) {
				$filePath = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::TMP_NAME];
				$newPath  = Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_STOCK_LOCATION . $fileName;
				move_uploaded_file($filePath, $newPath);
				$fullPath     = '/' . Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_STOCK_LOCATION . $fileName;
				if ($stockLocation->photo && file_exists(getcwd() . $stockLocation->photo)) {
					unlink(getcwd() . $stockLocation->photo);
				}
			}
			$stockGatewave = $stockLocationTable->findById($stockLocationId);
			$stockGatewave->setStockLocationName($data['stocklocationname']);
			$stockGatewave->setPartner($data['partner']);
			$stockGatewave->setCountry($data['country']);
			$stockGatewave->setCity($data['city']);
			$stockGatewave->setContact($data['contact']);
			$stockGatewave->setContactPhone($data['contact_phone']);
			$stockGatewave->setStockLocationType($data['stocklocationtype']);
			$stockGatewave->setStock($data['stock']);
			$stockGatewave->setShepherd($data['shepherd']);
			$stockGatewave->setAddress($data['address']);
			$updateDate         = Sss_Ultility_Common::getDateTimeNumber();
			// Process editing stock location
			$stockGatewave->setUpdatedDate($updatedDate);
			$stockGatewave->setPhoto($fullPath);
			$id = $stockLocationTable->save($stockGatewave);
			$StockLocationCompanyOwnerTable->deleteRowByStockLocation($stockLocationId);
			if(isset($id)){
				if(isset($paramOwner) && $paramOwner != '') {
					$otrs = new Sss_Ultility_OtrsServices();
					$instance = $instanceTable->getInstanceByStockLocation($stockLocationId);
					//add compnay owner to stock location
					$arrCompanyOwnerId = explode('_', $paramOwner);
					if (false != $arrCompanyOwnerId) { 
						for ($i = 0; $i < count($arrCompanyOwnerId); $i++) {
							$companyOwnerId = $arrCompanyOwnerId[$i];
							if ($companyOwnerId > 0 && $companyOwnerId != '') {
								$stockCompanyGatewave = new Application_Model_StockLocationCompanyOwner();
								$stockCompanyGatewave->setCompanyOwner($companyOwnerId);
								$stockCompanyGatewave->setStockLocation($stockLocationId);
								$StockLocationCompanyOwnerTable->save($stockCompanyGatewave);
							}
							//Assign company owner to group of instance
							$user = $accountTable->getById($companyOwnerId);
							if($instance && $user){
								$otrs->assignUser2Group(USER_SERVICE_ID,$user->otrs_user_id, null, $instance->otrs_group, USER_SERVICE, PASSWORD_SERVICE);
							}
						}
					}
				}
				return true;
			} else {
				return false;
			}
		}
		/**
		* put your comment there...
		* 
		* @param mixed $deleteRoomId
		* @param mixed $instance
		*/
		function deleteRoom($deleteRoomId,$instanceId)
		{
			$result = Resources::_('DELETE_ROOM_FAIL');
			$containerTable = new Shepherd_Model_Mapper_Container();
			$container = $containerTable->getContainer($deleteRoomId);
			if ($container && $container->photo)
				if (file_exists(getcwd() . $container->photo))
					unlink(getcwd() . $container->photo);
			$deleteId  = $containerTable->deleteRow((int) $deleteRoomId,$instanceId);
			if (isset($deleteId)) {
				$result = Resources::_('DELETE_ROOM_SUCCESSFULL');
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $valueHardware
		* @param mixed $roomId
		* @param mixed $description
		*/
		function assignHardwareInRoom($params, $arrAssignHardwareId, $roomId, $getDataContainer, $instanceId)
		{
			$errorMsg = '';
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$allocationTable = new Shepherd_Model_Mapper_Allocation();
			$containerTable = new Shepherd_Model_Mapper_Container();
			try {
				for ($i = 0; $i < count($arrAssignHardwareId); $i++) {
					$valueHardware = $arrAssignHardwareId[$i];
					if ($valueHardware > 0 && $valueHardware != '') {
						$startdt = date(DATETIME_MYSQL_FORMAT,$getDataContainer->created_date);
						$allocationUpdate = new Shepherd_Model_Allocation();
						$allocationUpdate->setHardware($valueHardware);
						$allocationUpdate->setDestination($roomId);
						$allocationUpdate->setStatus(1);
						$allocationUpdate->setSystemName(Sss_Ultility_SystemName::ROOMS);
						$allocationUpdate->setDescription($params['description']);
						$allocationUpdate->setStartdt($startdt);
						$checkInsert   = $allocationTable->checkAssignTo($valueHardware, $roomId, Sss_Ultility_SystemName::ROOMS);
						if ($checkInsert == true) {
							$allocatinId = $allocationTable->save($allocationUpdate, $instanceId);
							if($allocatinId){
								$room = $containerTable->getContainer($roomId);
								$hardware = $hardwareTable->getHardwareById($valueHardware);
								$hardwareUpdate = $hardwareTable->findById($valueHardware);
								$hardwareUpdate->setAllocation($hardware->stocklocationname.', '.$room->containername);
								$hardwareUpdate->setHardwareId($valueHardware);
								$hardwareTable->save($hardwareUpdate);
							}
						}
					}
				}
				$errorMsg = Resources::_('SENSOR_ATTACH_TO_ROOM_SUCCESSFULL');
			} catch(exception $e) {
				$errorMsg = Resources::_('SENSOR_ATTACH_TO_ROOM_FAIL');
			}
			return $errorMsg;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $arrHardwareId
		*/
		function assignHardware($arrHardwareId)
		{
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$inventoryTable = new Application_Model_Mapper_Inventory();
			$countExist = 0;
			$countDeleteSuccess = 0;
			$countDeleteFail = 0;
			for ($i = 0; $i < count($arrHardwareId); $i++) {
				$valueHardware = $arrHardwareId[$i];
				if ($valueHardware > 0 && $valueHardware != '') {
					//delete hardware
					$inventory = $inventoryTable->checkHardware($valueHardware);
					if($inventory != false){
						$countExist = $countExist + 1;
					} else {
						if (isset($valueHardware) && $valueHardware != -1) {
							$hardware = $hardwareTable->getHardwareById($valueHardware);
							if ($hardware->photo != null && $hardware->photo && file_exists(getcwd() . $hardware->photo)) {
								unlink(getcwd() . $hardware->photo);
							}
							$deleteId = $hardwareTable->deleteRow((int) $valueHardware);
							if (isset($deleteId)) {
								$countDeleteSuccess = $countDeleteSuccess + 1;
							} else {
								$countDeleteFail = $countDeleteFail + 1;
							}
						}
					}
				}
			}
			$messages = '';
			if($countDeleteSuccess > 0){
				$messages =  $messages.$countDeleteSuccess.Resources::_('DELETE_HARDWARE_SUCCESSFULL2');
			}
			if($countDeleteFail > 0){
				$messages = ($messages != '') ? $messages.'<div>'.$countDeleteFail.Resources::_('DELETE_HARDWARE_FAIL2').'</div>' : $messages.$countDeleteFail.Resources::_('DELETE_HARDWARE_FAIL2');
			}
			if($countExist > 0){
				$messages = ($messages != '') ? $messages.'<div>'.$countExist.Resources::_('HARDWARES_ASSIGN_STOCK_LOCATION').'</div>' : $messages.$countExist.Resources::_('HARDWARES_ASSIGN_STOCK_LOCATION');
			}
			return $messages;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $deleteHardwareId
		*/
		function deleteHardware($deleteHardwareId)
		{
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$inventoryTable = new Application_Model_Mapper_Inventory();
			$inventory = $inventoryTable->checkHardware($deleteHardwareId);
			if($inventory != false){
				$result = Resources::_('HARDWARE_ASSIGN_STOCK_LOCATION');
			} else {
				if (isset($deleteHardwareId) && $deleteHardwareId != -1) {
					$hardware = $hardwareTable->getHardwareById($deleteHardwareId);
					if ($hardware != false && $hardware->photo != null && $hardware->photo) {
						if (file_exists(getcwd() . $hardware->photo))
							unlink(getcwd() . $hardware->photo);
					}
					$deleteId = $hardwareTable->deleteRow((int) $deleteHardwareId);
					if (isset($deleteId)) {
						$result =  Resources::_('DELETE_HARDWARE_SUCCESSFULL1');
					} else {
						$result =  Resources::_('DELETE_HARDWARE_FAIL1');
					}
				}
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $userLogin
		* @param mixed $deleteFloorPlanId
		*/
		function deleteFloorplan($userLogin, $deleteFloorPlanId)
		{
			$containerTable = new Shepherd_Model_Mapper_Container();
			$result = Resources::_('DELETE_FLOOR_PLAN_FAIL');
			if ($userLogin) {
				if (isset($deleteFloorPlanId) && $deleteFloorPlanId != -1) { 
					$container = $containerTable->getContainer((int) $deleteFloorPlanId);
					if ($container->photo) {
						if (file_exists(getcwd() . $container->photo))
							unlink(getcwd() . $container->photo);
					}
					$checkRoomsInFloorPlan = $containerTable->checkRoomsInFloorPlan($deleteFloorPlanId);
					if ($checkRoomsInFloorPlan) {
						$deleteId       = $containerTable->deleteRow((int) $deleteFloorPlanId);
						if (isset($deleteId)) {
							$result = Resources::_('DELETE_FLOOR_PLAN_SUCCESSFULL');
						} else {
							$result = Resources::_('DELETE_FLOOR_PLAN_FAIL');
						}
					} else {
						$result = Resources::_('DELETE_FLOOR_PLAN_FAIL');
					}
				}
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $params
		* @param mixed $updateBy
		* @param mixed $container
		* @param mixed $fileUpload
		* @param mixed $fileUpload1
		* @param mixed $containerId
		*/
		function editFloorplan($params, $updateBy, $container, $fileUpload, $fileUpload1, $containerId,$instanceId)
		{
			$containerTable = new Shepherd_Model_Mapper_Container();
			$updateDate = strtotime(date('Y-m-d'));
			$containerUpdate = $containerTable->findById($containerId);
			$containerUpdate->setContainerName($params['containername']);
			$containerUpdate->setStockLocation(trim($params['stocklocation']));
			$containerUpdate->setUpdatedBy($updateBy);
			$containerUpdate->setUpdatedDate($updateDate);

			// Upload new file
			$photo = @array_shift(Sss_Ultility_Common::uploadFiles(
			@$fileUpload,
			array(
			'fullPath'    => Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER,
			'fullUrl'     => '/'.Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER
			)
			));

			// Delete new file if upload file success
			empty($photo) or unlink(getcwd().$container->{'photo'});
			$photo = empty($photo)?$container->{'photo'}:$photo['fullUrl'];
			$width = empty($photo)?$container->{'width'}:$photo['width'];
			$height = empty($photo)?$container->{'height'}:$photo['height'];
			$containerUpdate->setPhoto($photo);
			$containerUpdate->setWidth($width);
			$containerUpdate->setHeight($height);
			// Upload new file
			$photoFloorplan = @array_shift(Sss_Ultility_Common::uploadFiles(
			@$fileUpload1,
			array(
			'fullPath'    => Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER,
			'fullUrl'     => '/'.Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER
			)
			));
			// Delete new file if upload file success
			empty($photoFloorplan) or unlink(getcwd().$container->{'photofloorplan'});
			$photoFloorplan = empty($photoFloorplan)?$container->{'photofloorplan'}:$photoFloorplan['fullUrl'];
			$containerUpdate->setPhotoFloorplan($photoFloorplan);
			// Process adding new stock location
			$containerId    = $containerTable->save($containerUpdate,$instanceId);
			$message = isset($containerId) ? Resources::_('EDIT_FLOOR_PLAN_SUCCESSFULL') : Resources::_('EDIT_FLOOR_PLAN_FAIL');
			return $message;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $params
		* @param mixed $roomId
		* @param mixed $updateBy
		* @param mixed $updateDate
		* @param mixed $container
		* @param mixed $fileUpload
		* @param mixed $fileUpload1
		* @param mixed $userName
		*/
		function editRoom($params, $roomId, $updateBy, $updateDate, $container, $fileUpload, $fileUpload1, $userName, $instanceId)
		{
			$result = Resources::_('EDIT_ROOM_FAIL');
			$containerTable = new Shepherd_Model_Mapper_Container(); 
			$historyTable   = new Shepherd_Model_Mapper_History(); 
			$containerUpdate = $containerTable->findById($roomId,$instanceId);
			$containerUpdate->setContainerName($params['containername']);
			$containerUpdate->setTopValue($params['top_value']);
			$containerUpdate->setLeftValue($params['left_value']);
			$containerUpdate->setUpdatedBy($updateBy);
			$containerUpdate->setUpdatedDate($updateDate);
			$containerUpdate->setCompressorType($params['compressor_type']);
			$containerUpdate->setLastestRevision($params['lastest_revision']);
			$containerUpdate->setRoomValue($params['room_value']);
			$containerUpdate->setIsolationMaterial($params['isolation_material']);
			$containerUpdate->setCompressor($params['compressor']);
			// Upload new file
			$data = array();
			$photo = @array_shift(Sss_Ultility_Common::uploadFiles(
			@$fileUpload,
			array(
			'fullPath'    => Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER,
			'fullUrl'     => '/'.Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER
			)
			));
			// Delete new file if upload file success
			empty($photo) or unlink(getcwd().$container->{'photo'});
			$data['photo'] = empty($photo)?$container->{'photo'}:$photo['fullUrl'];
			$data['width'] = empty($photo)?$container->{'width'}:$photo['width'];
			$data['height'] = empty($photo)?$container->{'height'}:$photo['height'];

			// Upload new file
			$photoFloorplan = @array_shift(Sss_Ultility_Common::uploadFiles(
			@$fileUpload1,
			array(
			'fullPath'    => Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER,
			'fullUrl'     => '/'.Sss_Ultility_CommonViewParamater::FILE_PATH_PHOTO_CONTAINER
			)
			));
			// Delete new file if upload file success 
			empty($photoFloorplan) or unlink(getcwd().$container->{'photofloorplan'});
			$data['photofloorplan'] = empty($photoFloorplan)?$container->{'photofloorplan'}:$photoFloorplan['fullUrl'];

			// Process adding new stock location
			$containerUpdate->setPhoto($data['photo']);
			$containerUpdate->setPhotoFloorplan($data['photofloorplan']);
			$containerUpdate->setWidth($data['width']);
			$containerUpdate->setHeight($data['height']);
			$containerId = $containerTable->save($containerUpdate, $instanceId);
			if (isset($containerId)) {
				// Update changes
				$historyTable->setChanges(
					$userName,
					(array) $containerTable->getContainer($roomId, null, null, 1),
					(array) $container,
					array(
					'historytype'          => Sss_Ultility_Setting::HISTORY_TYPE_ROOM,
					'modified_date'        => Sss_Ultility_Common::getDateTimeNumber(),
					'created_by'           => $updateBy,
					'reference'            => $container->{'containerid'},
					),
					array(
					'containername'     => Resources::_('NAME'),
					'compressor_type'    => Resources::_('COMPRESSOR_TYPE'),
					'compressor'         => Resources::_('ROOM_COMPRESSOR_HOURS'),
					'lastest_revision'  => Resources::_('LATEST_REVISION'),
					'room_value'         => Resources::_('ROOM_VOLUME'),
					'isolation_material' => Resources::_('ISOLATION_MATERIAL'),
					'top_value'          => Resources::_('SHAPE'),
					'left_value'         => Resources::_('COORDS'),
					'photo'              => Resources::_('PHOTOFLOORPLAN'),
					'photofloorplan'     => Resources::_('PHOTO')
					),
					Sss_Ultility_Setting::HISTORY_FORMAT_ROOM,
					$instanceId
				);
				$result = Resources::_('EDIT_ROOM_SUCCESSFULL');
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $phototype
		* @param mixed $container
		* @param mixed $deleteImage
		*/
		function deleteImage($phototype, $container, $deleteImage, $instanceId)
		{
			$containerTable = new Shepherd_Model_Mapper_Container();
			$containerDelete = $containerTable->findById((int)$deleteImage);
			$result = Resources::_('DELETE_ROOM_IMAGE_FAIL');
			switch ($phototype) {
				case 'plan' :
					( !is_file(getcwd() . $container->{'photo'}) ) 
					or unlink(getcwd() . $container->{'photo'});
					$containerDelete->setPhoto(null);
					break;
				case 'photo' :
					( !is_file(getcwd() . $container->{'photofloorplan'}) ) 
					or unlink(getcwd() . $container->{'photofloorplan'});
					$containerDelete->setPhotoFloorplan(null);
					break;
			}
			$containerDelete->setContainerId((int)$deleteImage);
			$updateId       = $containerTable->save($containerDelete, $instanceId);
			if (isset($updateId)) {
				$result = Resources::_('DELETE_ROOM_IMAGE_SUCCESSFULL');
			}
		}
		/**
		* put your comment there...
		* 
		* @param mixed $params
		* @param mixed $fileName
		* @param mixed $allocationId
		*/
		function editHardwareInRoom($params, $fileName, $allocationId, $fullPath)
		{
			$result = Resources::_('EDIT_HARDWARE_FAIL');
			$allocationTable = new Shepherd_Model_Mapper_Allocation();
			$allocationUpdate = $allocationTable->findById($allocationId);
			$allocationUpdate->setAllocationId($allocationId);
			if($fileName){
				$allocationUpdate->setTopValueF($params['top_value_f']);
				$allocationUpdate->setLeftValueF($params['left_value_f']);
				$allocationUpdate->setTopValue($params['top_value']);
				$allocationUpdate->setLeftValue($params['left_value']);
				$allocationUpdate->setSensorIcon($fullPath);
				$allocationUpdate->setLayer($params['layer']);
				$allocationUpdate->setValueType($params['valuetype']);
				$allocationUpdate->setDescription($params['description']);
			} else {
				$allocationUpdate->setTopValueF($params['top_value_f']);
				$allocationUpdate->setLeftValueF($params['left_value_f']);
				$allocationUpdate->setTopValue($params['top_value']);
				$allocationUpdate->setLeftValue($params['left_value']);
				$allocationUpdate->setLayer($params['layer']);
				$allocationUpdate->setValueType($params['valuetype']);
				$allocationUpdate->setDescription($params['description']);
			}
			$id = $allocationTable->save($allocationUpdate);
			
			if (isset($id)) {
				$result = Resources::_('EDIT_HARDWARE_SUCCESSFULL');
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $shipmentId
		*/
		function deleteShipment($shipmentId, $instanceId)
		{
			$result = Resources::_('DELETE_SHIPMENT_FAIL');
			$shipmentTable = new Shepherd_Model_Mapper_Shipment();
			$alertTable    = new Shepherd_Model_Mapper_Alert();
			$productTable  = new Shepherd_Model_Mapper_Product();
			$documentTable = new Shepherd_Model_Mapper_Document();
			$allocationTable = new Shepherd_Model_Mapper_Allocation();
			$hardwareTable = new Application_Model_Mapper_Hardware();

			//get alert list for shipment
			$listAlert           = $alertTable->getList(Sss_Ultility_SystemName::SHIPMENTS,$shipmentId);

			//get product list for shipment
			$listProduct           = $productTable->getList($shipmentId);

			//get document list for shipment
			$listDocument           = $documentTable->getList($shipmentId);

			//get sensor list for shipment
			$listSensor           = $hardwareTable->getListByDestination($shipmentId, Sss_Ultility_SystemName::SHIPMENTS);
			if(count($listAlert) > 0 || count($listProduct) > 0 || count($listDocument) > 0 || count($listSensor) > 0 ) {
				$result = Resources::_('PROPERTIES_EXIST_TO_SHIPMENT');
			} else {
				$deleteId = $shipmentTable->deleteRow($shipmentId);
				if (isset($deleteId)) {
					$arrDelete = array(
					'destination = ?' => (int)$shipmentId,
					'systemname = ?' => Sss_Ultility_SystemName::SHIPMENTS);
					$deleteId      = $allocationTable->deleteRow(null, $arrDelete,$instanceId);
					$result = Resources::_('DELETE_SHIPMENT_SUCCESSFULL');
				} else {
					$result = Resources::_('DELETE_SHIPMENT_FAIL');
				} 
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $params
		* @param mixed $shipmentId
		* @param mixed $type
		*/
		function detachHardware($params, $shipmentId = null, $type = null, $instanceId = null)
		{
			if($shipmentId == null) {
				$shipmentId = $params['shipmentid'];
			}
			$result = Resources::_('DETACH_SENSOR_FAIL');
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$allocationTable = new Shepherd_Model_Mapper_Allocation();
			$shipmentTable = new Shepherd_Model_Mapper_Shipment();
			if ($type != null) {
				$hardwareId = $params['hardwareid'];
				$alloc = $allocationTable->getById($shipmentId, Sss_Ultility_SystemName::SHIPMENTS, $instanceId, $params['hardwareid']);
				$allocationUpdate = $allocationTable->findById($alloc->allocationid,$instanceId);
				$hardwareUpdate = $hardwareTable->findById($hardwareId);
				$date = new DateTime();
				$enddt = $date->format(DATETIME_MYSQL_FORMAT);
				$allocationUpdate->setStatus(0);
				$allocationUpdate->setNote($params['detach_location_name'.$hardwareId]);
				$allocationUpdate->setEnddt($enddt);
				$allocationUpdate->setHardware($hardwareId);
				$allocationUpdate->setDestination($shipmentId);
				$allocationUpdate->setSystemName(Sss_Ultility_SystemName::SHIPMENTS);
				$allocationTable->save($allocationUpdate, $instanceId);
				$hardwareUpdate->setDetachLocationName($params['detach_location_name'.$hardwareId]);
				if((int)$params['stocklocationid']) {
					$hardwareUpdate->setDetachLocationId($params['stocklocationid']);
				}
				$hardwareUpdate->setHardwareId($hardwareId);
				$id   = $hardwareTable->save($hardwareUpdate);
				$result = isset($id) ? Resources::_('DETACH_SENSOR_SUCCESSFULL') : Resources::_('DETACH_SENSOR_FAIL');
			} else {
				$hardwareIds = $params['hardwareid'];
				$listHardwareOfShipment = $hardwareTable->getListByDestination($params['shipmentid'], Sss_Ultility_SystemName::SHIPMENTS);
				$allocs = $allocationTable->getById($shipmentId, Sss_Ultility_SystemName::SHIPMENTS, $instanceId, $params['hardwareid']);
				if($allocs) {
					$allocationUpdates = $allocationTable->findById($allocs->allocationid);
				}
				$hardwareUpdates = $hardwareTable->findById($hardwareIds);
				try {
					if($allocs) {
						foreach ($listHardwareOfShipment as $h) {
							$allocationUpdates->setStatus(0);
							$allocationUpdates->setNote(@$params['txtLocation'][$shipmentId]);
							$allocationUpdates->setHardware((int) $h['hardwareid']);
							$allocationUpdates->setDestination($shipmentId);
							$allocationUpdates->setSystemName(Sss_Ultility_SystemName::SHIPMENTS);
							$allocationTable->save($allocationUpdates, $instanceId);
							$hardwareUpdates->setDetachLocationId(@$params['txtOrigin'][$shipmentId]);
							$hardwareUpdates->setDetachLocationName(@$params['txtLocation'][$shipmentId]);
							$hardwareUpdates->setHardwareId((int) $h['hardwareid']);
							$id   = $hardwareTable->save($hardwareUpdates);
						}
						//update field enddt in table allocations
						if(empty($params['txtEnddate'][$shipmentId])) {
							$date = new DateTime();
							$enddt = $date->format(DATETIME_MYSQL_FORMAT);
						} else {
							$date = explode("/",$params['txtEnddate'][$shipmentId]);
							$str = $date[1] . '/' . $date[0].'/'.$date[2];
							$enddt = date(DATETIME_MYSQL_FORMAT,strtotime($str));
						}
						$allocationUpdates->setEnddt($enddt);
						$allocationUpdates->setDestination($shipmentId);
						$allocationTable->save($allocationUpdates, $instanceId);
						// End update
					}
					if(isset($params['shipmentid']) && $params['shipmentid'] > 0) {
						$shipmentUpdate = $shipmentTable->findById($shipmentId);
						$shipmentUpdate->setEndDate(Sss_Ultility_Common::getDateTimeNumber(empty($params['txtEnddate'][$shipmentId])?time():$params['txtEnddate'][$shipmentId]));
						$shipmentUpdate->setShipmentId($shipmentId);
						$id   = $shipmentTable->save($shipmentUpdate, $instanceId);
					}
					$result = Resources::_('DETACH_SENSOR_SUCCESSFULL');
				}
				catch (exception $e){
					$result = Resources::_('DETACH_SENSOR_FAIL');
				}
			}
			return $result;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $row
		* @return int
		*/
		function rmaProccess($row)
		{
			$alertTable    = new Shepherd_Model_Mapper_Alert();
			$productTable  = new Shepherd_Model_Mapper_Product();
			$documentTable = new Shepherd_Model_Mapper_Document();
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$listAlertShipment    = array();
			$listProductShipment  = array();
			$listDocumentShipment = array();
			$listSensorShipment   = array();
			foreach ((array) $row as $r) {
				//get alert list for shipment
				$listAlert           = $alertTable->getList(Sss_Ultility_SystemName::SHIPMENTS, $r['shipmentid']);
				$listAlertShipment[] = count($listAlert);

				//get product list for shipment
				$listProduct           = $productTable->getList($r['shipmentid']);
				$listProductShipment[] = count($listProduct);

				//get document list for shipment
				$listDocument           = $documentTable->getList($r['shipmentid']);
				$listDocumentShipment[] = count($listDocument);

				//get sensor list for shipment
				$listSensor           = $hardwareTable->getListByDestination($r['shipmentid'], Sss_Ultility_SystemName::SHIPMENTS);
				$listSensorShipment[] = $listSensor;

			}
			//get stock location 
			$stockLocation = $stockLocationTable->getAllStockLocation();

			$ArrStockLocation = array();
			$dataAuto = '';
			foreach($stockLocation as $sl) {
				$ArrStockLocation[$sl['stocklocationname']]= $sl['stocklocationid'];
			}
			foreach ($ArrStockLocation as $key=>$value) {
				$dataAuto = $dataAuto."$key|$value#";
			}
			$dataAuto = substr($dataAuto, 0 ,strlen($dataAuto) - 1);
			$countSensor = 0;
			foreach($listSensorShipment as $ls) {
				foreach($ls as $s) {
					$countSensor = $countSensor + 1;
				}
			}

			//get sensor list by shipment
			$hardwareByShipment = $hardwareTable->getHardwareByDestinationGraph('', Sss_Ultility_SystemName::SHIPMENTS);
			$chartsByShipment = array();
			$index = 0;
			foreach ($hardwareByShipment as $tmp) {
				$chartIds = '';  
				$chartList =    $hardwareTable->getChartIds($tmp['hardwareid'], $tmp['systemtypeid']);
				if($chartList) {
					foreach($chartList as $c) {
						$chartIds = ($chartIds == '') ? $c['chart'] : $chartIds . ',' .  $c['chart'];
					}
				}
				$tmp['chart'] = $chartIds; 
				$chartsByShipment[$index]     = $tmp;
				$index = $index + 1;
			}
			$countSensor = ($countSensor == 0) ? count($row) : $countSensor;
			$arrRelateShipment = array();
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::ROW_ALERT_SHIPMENT] = $listAlertShipment;
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::ROW_PRODUCT_ITEM] = $listProductShipment;
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::ROW_DOCUMENT_ITEM] = $listDocumentShipment;
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::ROW_SENSOR_ITEM] = $listSensorShipment;
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::AUTOCOMPLETE] = $dataAuto;
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::HARDWARE_BY_SHIPMENT] = $chartsByShipment;
			$arrRelateShipment[Sss_Ultility_CommonViewParamater::ROW_SENSOR_ITEM_COUNT] = $countSensor;
			return $arrRelateShipment;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $params
		* @param mixed $fileName
		* @param mixed $fullPath
		* @param mixed $createBy
		* @param mixed $document
		* @param mixed $shipmentId
		* @param mixed $documentId
		*/
		function addEditDocument($params, $fileName, $fullPath, $createBy, $document, $shipmentId, $documentId, $instanceId)
		{
			$message = '';
			$documentTable = new Shepherd_Model_Mapper_Document();
			if($documentId != -1){
				$documentGateway = $documentTable->findById($documentId);
			} else {
				$documentGateway = new Shepherd_Model_Document();
			}
			// Process add/edit new document
			if ($fileName) {
				if ($document->path) {
					if (file_exists(getcwd() . $document->path))
						unlink(getcwd() . $document->path);
				}
				$documentGateway->setDocumentName($params['documentname']);
				$documentGateway->setCreatedDate(Sss_Ultility_Common::getDateTimeNumber());
				$documentGateway->setCreatedBy($createBy);
				$documentGateway->setUpdatedBy($createBy);
				$documentGateway->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
				$documentGateway->setShipment($shipmentId);
				$documentGateway->setPath($fullPath);
			} else {
				$documentGateway->setDocumentName($params['documentname']);
				$documentGateway->setCreatedDate(Sss_Ultility_Common::getDateTimeNumber());
				$documentGateway->setCreatedBy($createBy);
				$documentGateway->setUpdatedBy($createBy);
				$documentGateway->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
				$documentGateway->setShipment($shipmentId);
			} 
			if ($documentId != -1) {
				$id = $documentTable->save($documentGateway, $instanceId);
				$message = isset($id) ? Resources::_('EDIT_DOCUMENT_SUCCESSFULL') : Resources::_('EDIT_DOCUMENT_FAIL');
			} else {
				$id = $documentTable->save($documentGateway, $instanceId);
				$message = isset($id) ? Resources::_('ADD_DOCUMENT_SUCCESSFULL') : Resources::_('ADD_DOCUMENT_FAIL');
			}
			return $message;
		}

		function addShipment($params, $createBy, $status, $shipmenttypeId, $monitorId, $instanceId)
		{
			$shipmentTable = new Shepherd_Model_Mapper_Shipment();
			$shipmentConstructor = new Shepherd_Model_Shipment();
			if(isset($params['txtOrigin']) && !empty($params['txtOrigin'])) {
				$orgin = $params['origin'];
				$orgin = empty($orgin) ? $params['txtOrigin'] : $orgin;
			} else {
				$orgin = 0;
			}
			if(isset($params['txtDestination']) && !empty($params['txtDestination'])){
				$destination = $params['destination'];
				$destination = empty($destination) ? $params['txtDestination'] : $destination;
			} else{
				$destination = 0;
			}
			$shipmentConstructor->setShipmentName(addslashes($params['shipmentname']));
			$shipmentConstructor->setShipDate(Sss_Ultility_Common::getDateTimeNumber($params['ship_date']));
			$shipmentConstructor->setOrigin(is_numeric($orgin) ? $orgin : 0);
			$shipmentConstructor->setOriginText(is_numeric($orgin) ? null : $orgin);
			$shipmentConstructor->setDestination(is_numeric($destination) ? $destination : 0);
			$shipmentConstructor->setDestinationText(is_numeric($destination) ? null : $destination);
			$shipmentConstructor->setInternalRef(addslashes($params['internal_ref']));
			$shipmentConstructor->setReferenceNumber(empty($params['reference_number']) ? null : addslashes($params['reference_number']));
			$shipmentConstructor->setSupplierRef(empty($params['supplier_ref']) ? null : addslashes($params['supplier_ref']));
			$shipmentConstructor->setStatus($status);
			$shipmentConstructor->setShipmentType($params['shipmenttype']);
			$shipmentConstructor->setDescription(trim(addslashes($params['description'])));
			$shipmentConstructor->setDateOfEntry(empty($params['date_of_entry']) ? null : Sss_Ultility_Common::getDateTimeNumber($params['date_of_entry']));
			$shipmentConstructor->setRevenue(trim(addslashes($params['revenue'])));
			$shipmentConstructor->setVolume(is_numeric($params['volume']) ? $params['volume'] : 0);
			if ($shipmenttypeId == -1) {
				$shipmentConstructor->setCreatedBy($createBy);
				$shipmentConstructor->setUpdatedBy($createBy);
				$shipmentConstructor->setCreatedDate(Sss_Ultility_Common::getDateTimeNumber());
				$shipmentConstructor->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
			} else {
				$shipmentConstructor->setUpdatedBy($createBy);
				$shipmentConstructor->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
			}
			if(isset($params['origin']) && isset($params['destination']) && $params['origin'] == $params['destination'] && $params['origin'] != '' && $params['destination'] != ''){
				$this->view->assign(Sss_Ultility_CommonViewParamater::NOTICEMSG, Resources::_('SHIPMENT_NOT_HAVE_TWO_ADDRESS_SAME'));
				$arrResult['shipmentid'] = 0;
			} else {
				$shipmentId = $shipmentTable->save($shipmentConstructor, $instanceId);
				$message = isset($shipmentId) ? Resources::_('ADD_SHIPMENT_SUCCESSFULL') : Resources::_('ADD_SHIPMENT_FAIL');
				$arrResult['shipmentid'] = $shipmentId;
			}
			$arrResult['message'] = $message;
			return $arrResult;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $params
		* @param mixed $createBy
		* @param mixed $shipmentId
		*/
		function editShipment($params, $createBy, $shipmentId, $instanceId)
		{
			$shipmentTable = new Shepherd_Model_Mapper_Shipment();
			$shipmentUpdate = $shipmentTable->findById($shipmentId);
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			if(isset($params['txtOrigin']) && !empty($params['txtOrigin'])){
				$orgin = $params['origin'];
				$stockLocationByOrigin =  $stockLocationTable->select($orgin);
				if(trim($stockLocationByOrigin->stocklocationname) != trim($params['txtOrigin'])) {
					$orgin = $params['txtOrigin'] ;
				}
				$orgin = empty($orgin) ? 0 : $orgin;
			} else{
				$orgin = 0;
			}
			if(isset($params['txtDestination']) && !empty($params['txtDestination'])) {
				$destination = $params['destination'];
				$stockLocationByDestination =  $stockLocationTable->select($destination);
				if(trim($stockLocationByDestination->stocklocationname) != trim($params['txtDestination'])){
					$destination = $params['txtDestination'] ;
				}
				$destination = empty($destination) ? 0 : $destination;
			} else{
				$destination = 0;
			}
			// Process update shipment
			$shipmentUpdate->setShipmentName(addslashes($params['shipmentname']));
			$shipmentUpdate->setShipDate(Sss_Ultility_Common::getDateTimeNumber($params['ship_date']));
			$shipmentUpdate->setOrigin(is_numeric($orgin) ? $orgin : 0);
			$shipmentUpdate->setOriginText(is_numeric($orgin) ? null : $orgin);
			$shipmentUpdate->setDestination(is_numeric($destination) ? $destination : 0);
			$shipmentUpdate->setDestinationText(is_numeric($destination) ? null : $destination);
			$shipmentUpdate->setCreatedBy($createBy);
			$shipmentUpdate->setCreatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$shipmentUpdate->setInternalRef(addslashes($params['internal_ref']));
			$shipmentUpdate->setReferenceNumber(empty($params['reference_number']) ? null : addslashes($params['reference_number']));
			$shipmentUpdate->setSupplierRef(empty($params['supplier_ref']) ? null : addslashes($params['supplier_ref']));
			$shipmentUpdate->setStatus(1);
			$shipmentUpdate->setShipmentType($params['shipmenttype']);
			$shipmentUpdate->setDescription(trim(addslashes($params['description'])));
			$shipmentUpdate->setDateOfEntry(empty($params['date_of_entry']) ? null : Sss_Ultility_Common::getDateTimeNumber($params['date_of_entry']));
			$shipmentUpdate->setRevenue(trim(addslashes($params['revenue'])));
			$shipmentUpdate->setVolume(is_numeric($params['volume']) ? $params['volume'] : 0);
			if($orgin == $destination && $ogrin != 0 && $destination != 0) {
				$message = Resources::_('SHIPMENT_NOT_HAVE_TWO_ADDRESS_SAME');
			} else {
				$updateId    = $shipmentTable->save($shipmentUpdate, $instanceId);
				$message = isset($updateId) ? Resources::_('EDIT_SHIPMENT_SUCCESSFULL') : Resources::_('EDIT_SHIPMENT_FAIL');
			}
			return $message;
		}
		/**
		* put your comment there...
		* 
		* @param mixed $userInformation
		* @return int
		*/
		function gethardwareIds($userInformation)
		{
			//path file
			$fileName = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::NAME];
			if ($fileName) {
				$filePath = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::TMP_NAME];
				$newPath  = Sss_Ultility_CommonViewParamater::FILE_PATH . $fileName;
				move_uploaded_file($filePath, $newPath);
				$hardwareIds = Sss_Ultility_Common::importData($userInformation['accountid'], $newPath, null);
			}
			return $hardwareIds;
		}
		function arractionButton($userInformation)
		{
			//action button
			$actionbuttons = array(
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADD, 'add-hardware', Resources::_('ADD_NEW_HARDWARE')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::EXPORT, 'hardware-export?export=1', Resources::_('EXPORT')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::PRINTF, 'hardware-export?print=1', Resources::_('PRINT')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::SEARCH, 'javascript:hideShow(this);', Resources::_('SEARCH'))
			);
			
			if($userInformation['accounttype'] != Sss_Ultility_Setting::ACCOUNT_OVIS){
				$actionbuttons = array(
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::EXPORT, 'hardware-export?export=1', Resources::_('EXPORT')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::PRINTF, 'hardware-export?print=1', Resources::_('PRINT')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::SEARCH, 'javascript:hideShow(this);', Resources::_('SEARCH'))
				);
			}
			return $actionbuttons;
		}
		function arrData($createBy,$hardwareId,$params)
		{
			// Process add history
			$historyContructor = new Application_Model_History();
			$historyContructor->setHistoryType(Sss_Ultility_Setting::HISTORY_TYPE_RMA);
			$historyContructor->setModifiedDate(Sss_Ultility_Common::getDateTimeNumber());
			$historyContructor->setCreatedBy($createBy);
			$historyContructor->setHardware($hardwareId);
			$historyContructor->setNote($params['note']);
			return $historyContructor;
		}
		function addInventory($stockLocationId,$params,$createBy,$hardwareId)
		{
			$inventoryTable = new Application_Model_Mapper_Inventory();
			$inventoryContructor = new Application_Model_Inventory();
			//add inventory when add hardware successfull
			if ($stockLocationId != -1) {
				$inventoryContructor->setStockLocation($stockLocationId);
				$inventoryContructor->setHardware($hardwareId);
				$inventoryContructor->setIsactivated(1);
				$inventoryContructor->setFromDate(Sss_Ultility_Common::getDateTimeNumber());
				$inventoryContructor->setToDate(0);
				$inventoryContructor->setAssigneBy($createBy);
				$inventoryContructor->setStatus($params['status']);
				$inventoryContructor->setNote($params['note']);
				$inventoryTable->save($inventoryContructor);
			}
		}
		function addTicketByHardware($arrLinkId,$hardwareId)
		{
			$linkTable = new Application_Model_Mapper_Link();
			if (false != $arrLinkId) {
			for ($i = 0; $i < count($arrLinkId); $i++) {
				$linkId = $arrLinkId[$i];
				if ($linkId > 0 && $linkId != '') {
					$linkValue = $linkTable->findById($linkId);
					$linkValue->setHardware($hardwareId);
					$linkId = $linkTable->save($linkValue);
				}
			}
		}
		}
		function addDocumentByHardware($arrDocumentId,$hardwareId)
		{
			$referenceTable = new Application_Model_Mapper_References();
			if (false != $arrDocumentId) {
				for ($i = 0; $i < count($arrDocumentId); $i++) {
					$documentId = $arrDocumentId[$i];
					if ($documentId > 0 && $documentId != '') {
						$referenceContructor = new Application_Model_References();
						$referenceContructor->setReferenceType(Sss_Ultility_Setting::DOCUMENT_HARDWARE);
						$referenceContructor->setDocument($documentId);
						$referenceContructor->setDestination($hardwareId);
						$checkReference = $referenceTable->checkReference($hardwareId, $documentId, Sss_Ultility_Setting::DOCUMENT_HARDWARE);
						if ($checkReference == false) {
							$referenceTable->save($referenceContructor);
						}
					}
				}
			}
		}
		function deleteProduct($userInformation,$productTable,$deleteProductId,$instanceId)
		{
			if ($userInformation->username && isset($deleteProductId) && $deleteProductId != -1) {
				$deleteId     = $productTable->deleteRow((int) $deleteProductId,$instanceId);
				$message = isset($deleteId) ? Resources::_('DELETE_PRODUCT_SUCCESSFULL') : Resources::_('DELETE_PRODUCT_FAIL');
			}
			return $message;
		}
		function deleteDocument($userInformation,$documentTable,$deleteDocumentId,$instanceId)
		{
			if ($userInformation->username && isset($deleteDocumentId) && $deleteDocumentId != -1) {
				$deleteId      = $documentTable->deleteRow($deleteDocumentId, $instanceId);
				$message = isset($deleteId) ? Resources::_('DELETE_DOCUMENT_SUCCESSFULL') : Resources::_('DELETE_DOCUMENT_FAIL');
			}
			return $message;
		}
		function removeSensor($userInformation,$shipmentId,$allocationTable,$deleteSensorId,$instanceId)
		{
			if ($userInformation->username && isset($deleteSensorId) && $deleteSensorId != -1) {
				$arrId    = array(
				'hardware = ?' => (int) $deleteSensorId,
				'destination = ?' => (int) $shipmentId,
				'systemname = ?' => Sss_Ultility_SystemName::SHIPMENTS
				);
				$deleteId = $allocationTable->deleteRow(null,$arrId, $instanceId);
				$message = isset($deleteId) ? Resources::_('DELETE_HARDWARE_SUCCESSFULL') : Resources::_('DELETE_HARDWARE_FAIL');
			}
			return $message;
		}
		function assignHardwareToItem($arrAssignHardwareId,$shipment,$shipmentId,$allocationTable,$hardwareTable,$inventoryTable,$params,$stocklocationTable, $instanceId)
		{
			for ($i = 0; $i < count($arrAssignHardwareId); $i++) {
			$valueHardware = $arrAssignHardwareId[$i];
			if ($valueHardware > 0 && $valueHardware != '') {
				$allocationConstructor = new Shepherd_Model_Allocation();
				$startdt = date(DATETIME_MYSQL_FORMAT,$shipment->ship_date);
				$allocationConstructor->setHardware($valueHardware);
				$allocationConstructor->setDestination($shipmentId);
				$allocationConstructor->setStatus(1);
				$allocationConstructor->setSystemName(Sss_Ultility_SystemName::SHIPMENTS);
				$allocationConstructor->setDescription($params['description']);
				$allocationConstructor->setStartdt($startdt);
				$checkInsert = $allocationTable->checkAssignTo($valueHardware, $shipmentId, Sss_Ultility_SystemName::SHIPMENTS);
				if ($checkInsert == true) {
					$allocatinId = $allocationTable->save($allocationConstructor, $instanceId);
					//get hardware
					$hardware = $hardwareTable->getHardwareById($valueHardware);
					$updateHardware = $hardwareTable->findById($valueHardware);
					if($allocatinId){
						if($shipment->origin != 0 && $shipment->destination != 0){
							$origin =  $stocklocationTable->select($shipment->origin);
							$destination =  $stocklocationTable->select($shipment->destination);
							$allocationName = $hardware->stocklocationname.', '.$shipment->shipmentname.'( '.Resources::_('TITLE_FROM').' '.$origin->stocklocationname.' '.Resources::_('TITLE_TO').' '.$destination->stocklocationname.')';
						}else{
							$allocationName = $hardware->stocklocationname.', '.$shipment->shipmentname;
						}
						$updateHardware->setAllocation($allocationName);
						$hardwareTable->save($updateHardware);
					}
					//process update hardware
					if ($shipment->shipmenttype == Sss_Ultility_Setting::RMA) {
						$updateHardware->setStatus(Sss_Ultility_Setting::OVIS_RMA);
						$updateHardware->setHardwareId($valueHardware);
						$id            = $hardwareTable->save($updateHardware);
						if (isset($id)) {
								$arrInventoryId = array(
										'stocklocation' => (int) $hardware->stocklocationid,
										'isactivated' => true,
										'hardware' => $valueHardware
								);
								$getInventoryId = $inventoryTable->findIdByData($arrInventoryId);
								if($getInventoryId) {
									$updateInventory = $inventoryTable->findById($getInventoryId->inventoryid);
									$updateInventory->setStatus(Sss_Ultility_Setting::OVIS_RMA);
									$inventoryId = $inventoryTable->save($updateInventory);
								}
							}
						}
					}
				}
			}
		}
		function getQuery($status,$shipmentId,$shipmentdetail,$monitorId)
		{
			//get query string
			$strAction   = 'shipment';
			$queryString = "?shipmentid=" . $shipmentId;
			if($status != -1) {
				$strAction   = 'rma';
				$queryString = "?shipmentid=" . $shipmentId."&status=" . Sss_Ultility_Setting::RMA;
			}
			if ($shipmentdetail != -1) {
				$strAction   = Sss_Ultility_CommonViewParamater::ACTION_SHIPMENT_DETAIL;
				$queryString = "?shipmentid=" . $shipmentId . '&' . Sss_Ultility_CommonViewParamater::SHIPMENT_DETAIL . '=1';
				if($status != -1) {
					$strAction   = 'rma';
					$queryString = "?shipmentid=" . $shipmentId . '&' . Sss_Ultility_CommonViewParamater::SHIPMENT_DETAIL . '=1'.'&'.'status' . "=" . Sss_Ultility_Setting::RMA;
				}
			}
			if($monitorId == 1) {
				$strAction = "dynamicmonitoring";
				$queryString = $queryString.'&'.Sss_Ultility_CommonViewParamater::MONITORING_LOCALIZATION . '=1';
			}
			$result = array($strAction,$queryString);
			return $result;
		}
		function getChartsByShipment($hardwareByShipment,$hardwareTable)
		{
			$chartsByShipment = array();
			$index = 0;
			foreach ($hardwareByShipment as $tmp) {
				$chartIds = '';
				$chartList =    $hardwareTable->getChartIds($tmp['hardwareid'], $tmp['systemtypeid']);
				if($chartList){
					foreach($chartList as $c){
						if($chartIds == ''){
							$chartIds = $c['chart'];
						}else{
							$chartIds = $chartIds . ',' .  $c['chart'];
						}
					}
				}
				$tmp['chart'] = $chartIds;
				$chartsByShipment[$index]     = $tmp;
				$index = $index + 1;
			}
			return $chartsByShipment;
		}
		function updateHardwareDetach($params,$hardwareTable)
		{
			//update hardware when detach
			if(isset($params['hardwareid']) && isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])){
				$hardwareIds = $params['hardwareid'];
				$stockLocationIds =  $params['stocklocationid'];
				$arrHardwareIds = explode(',', $hardwareIds);
				$arrStockLocationIds = explode(',', $stockLocationIds);
				$id;
				try{
					for ($i = 0; $i < count($arrHardwareIds); $i++) {
						$hardwareUpdate = $hardwareTable->findById((int) $arrHardwareIds[$i]);
						$hardwareUpdate->setDetachLocationName($params['detach_location_name'.$arrHardwareIds[$i]]);
						$hardwareUpdate->setStatus(Sss_Ultility_Setting::HARDWARE_STATUS_DETACH);
						$hardwareUpdate->setDetachLocationId(null);
						if($arrStockLocationIds[$i] != '' && (int)$arrStockLocationIds[$i]) {
							$hardwareUpdate->setDetachLocationId($arrStockLocationIds[$i]);
						}
						$id   = $hardwareTable->save($hardwareUpdate);
					}
					$message = Resources::_('DETACH_SENSOR_SUCCESSFULL');
				}
				catch (exception $e){
					$message = Resources::_('DETACH_SENSOR_FAIL');
				}
			}
			return $message;
		}
		function getInformationShipmentHistory($row,$alertTable,$productTable,$documentTable,$hardwareTable)
		{
			$listAlertShipment    = array();
			$listProductShipment  = array();
			$listDocumentShipment = array();
			$listSensorShipment   = array();
			foreach ((array) $row as $r) {
				//get alert list for shipment
				$listAlert           = $alertTable->getList(Sss_Ultility_SystemName::SHIPMENTS, $r['shipmentid']);
				$listAlertShipment[] = count($listAlert);
				//get product list for shipment
				$listProduct           = $productTable->getList($r['shipmentid']);
				$listProductShipment[] = count($listProduct);
				//get document list for shipment
				$listDocument           = $documentTable->getList($r['shipmentid']);
				$listDocumentShipment[] = count($listDocument);
				//get sensor list for shipment
				$listSensor           = $hardwareTable->getListByDestination($r['shipmentid'], Sss_Ultility_SystemName::SHIPMENTS);
				$listSensorShipment[] = $listSensor;
			}
			$result = array($listAlertShipment,$listProductShipment,$listDocumentShipment,$listSensorShipment);
			return $result;
		}

		function processInsertHistory($params,$hardware,$createBy)
		{
			$historyTable = new Application_Model_Mapper_History();
			$vendorTable = new Application_Model_Mapper_Vendor();
			$systemTypeTable = new Application_Model_Mapper_SystemType();
			$hardwareId = $hardware->hardwareid;
			if (isset($params['hardwarename']) && $hardware->hardwarename != $params['hardwarename']) {
				$note = Resources::_('NAME') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->hardwarename . "' " . Resources::_('TO_HISTORY') . " '" . $params['hardwarename'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['serial_number']) && $hardware->serial_number != $params['serial_number'] && $params['serial_number'] != '') {
				$note = Resources::_('SERIAL_NUMBER') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->serial_number . "' " . Resources::_('TO_HISTORY') . " '" . $params['serial_number'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['vendor']) && $hardware->vendor != $params['vendor'] && $params['vendor'] != 0) {
				$newName = $vendorTable->findById($params['vendor'])->vendorname;
				$note = Resources::_('VENDOR') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->vendorname . "' " . Resources::_('TO_HISTORY') . " '" . $newName . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['buyer']) && $hardware->buyer != $params['buyer']) {
				$note = Resources::_('USER') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->buyer . "' " . Resources::_('TO_HISTORY') . " '" . $params['buyer'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['hardwaretype']) && $hardware->hardwaretype != $params['hardwaretype'] && $params['hardwaretype'] != 0) {
				$newName = $systemTypeTable->findById($params['hardwaretype'])->typename;
				$note = Resources::_('TYPE') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->hardwaretype_name . "' " . Resources::_('TO_HISTORY') . " '" . $newName . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['status']) && $hardware->status != $params['status']) {
				$newName = $systemTypeTable->findById($params['status'])->typename;
				$note = Resources::_('STATUS') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->status_name . "' " . Resources::_('TO_HISTORY') . " '" . $newName . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['soft_version']) && $hardware->soft_version != $params['soft_version']) {
				$note = Resources::_('SOFTW_VERSION') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->soft_version . "' " . Resources::_('TO_HISTORY') . " '" . $params['soft_version'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['hard_version']) && $hardware->hard_version != $params['hard_version']) {
				$note = Resources::_('HARDW_VERSION') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->hard_version . "' " . Resources::_('TO_HISTORY') . " '" . $params['hard_version'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['owner']) && $hardware->owner != $params['owner']) {
				$note = Resources::_('OWNER') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->owner . "' " . Resources::_('TO_HISTORY') . " '" . $params['owner'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
			//process insert history
			if (isset($params['note']) && $hardware->note != $params['note']) {
				$note = Resources::_('NOTE') . ' ' . Resources::_('FROM_HISTORY') . " '" . $hardware->note . "' " . Resources::_('TO_HISTORY') . " '" . $params['note'] . "'";
				$data = Sss_Ultility_Common::dataHistory($note, $hardwareId, $createBy);
				$id = $historyTable->save($data);
			}
		}

		function addInventoryEditHardware($stockLocationId,$hardware,$createBy,$hardwareId)
		{
			$inventoryTable = new Application_Model_Mapper_Inventory();
			$inventoryContructor = new Application_Model_Inventory();
			if ($stockLocationId != -1 && $stockLocationId != $hardware->stocklocationid && $stockLocationId != 0) {
				$arrInventoryId = array(
						'stocklocation' => $hardware->stocklocationid > 0 ? (int) $hardware->stocklocationid : 0,
						'isactivated' => 1,
						'hardware' => $hardwareId
				);
				//get Id of inventory
				$id = $inventoryTable->findIdByData($arrInventoryId);
				if(!empty($id)) {
					$update = $inventoryTable->findById($id->inventoryid);
					//update inventory
					$update->setToDate(Sss_Ultility_Common::getDateTimeNumber());
					$update->setIsactivated(0);
					$inventoryId = $inventoryTable->save($update);
				}

				//Insert new data
				$stock = $stockLocationId == null ? 0 : $stockLocationId;
				$inventoryContructor->setStockLocation($stock);
				$inventoryContructor->setHardware($hardwareId);
				$inventoryContructor->setIsactivated(1);
				$inventoryContructor->setFromDate(Sss_Ultility_Common::getDateTimeNumber());
				$inventoryContructor->setToDate(0);
				$inventoryContructor->setAssigneBy($createBy);
				$inventoryContructor->setStatus($params['status']);
				$inventoryContructor->setNote($params['note']);
				$inventoryId = $inventoryTable->save($inventoryContructor);
			} else {
				$arrInventoryId = array(
						'stocklocation' => (int) $hardware->stocklocationid,
						'isactivated' => true,
						'hardware' => $hardwareId
				);
				//get Id of inventory
				$id = $inventoryTable->findIdByData($arrInventoryId);
				if($id) {
					$update = $inventoryTable->findById($id->inventoryid);
					$update->setStatus($params['status']);
					$update->setAssigneBy($createBy);
					$update->setNote($params['note']);
					$inventoryId = $inventoryTable->save($update);
				}
			}
			if ($stockLocationId == 0) {
				$arrInventoryDeleteId = array(
					'stocklocation = ?' => $hardware->stocklocationid,
					'hardware = ?'      => $hardwareId,
					'isactivated = ?'   => 1
				);
				$inventoryTable->deleteRow(null,$arrInventoryDeleteId);
			}
		}

		function editHardware($hardwareId,$hardware,$params,$stockLocation,$createBy,$stockLocationId)
		{
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$hardwareUpdate = $hardwareTable->findById($hardwareId);
			//upload image
			$fullPath = null;
			$fileName = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::NAME];
			if ($fileName) {
				if ($hardware->photo) {
					if (file_exists(getcwd() . $hardware->photo))
						unlink(getcwd() . $hardware->photo);
				}
				$filePath = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::TMP_NAME];
				$newPath = Sss_Ultility_CommonViewParamater::FILE_PATH_HARDWARE . $fileName;
			
				move_uploaded_file($filePath, $newPath);
				$fullPath = '/' . Sss_Ultility_CommonViewParamater::FILE_PATH_HARDWARE . $fileName;
			}
			if ($fileName == '') {
				$fullPath = $hardware->photo;
			}

			$allocation = Resources::_('NOT_ALLOCATED');
			if ($stockLocation != false && $hardware != false) {
				if (isset($params['allocation'])) {
					if ($hardware->stocklocationid == $params['stocklocationid']) {
						$allocation = $params['allocation'];
					} else {
						$allocation = $stockLocation->stocklocationname;
					}
				} else {
					$allocation = $hardware != null ? $hardware->allocation : Resources::_('NOT_ALLOCATED');
				}
			} else if ($stockLocation != false) {
				$allocation = $stockLocation->stocklocationname;
			}

			if ($stockLocationId == 0 && $hardware != false) {
				$allocation = $hardware->allocation;
			}
			if (isset($params['hardwarename'])) {
				$hardwareName = $params['hardwarename'];
			} else {
				$hardwareName = $hardware->hardwarename;
			}
			if (isset($params['serial_number']) && $params['serial_number'] != '') {
				$serialNumber = $params['serial_number'];
				$hardwareUpdate->setSerialNumber(addslashes($serialNumber));
			} else {
				$serialNumber = $hardware->serial_number;
			}
			if (isset($params['hardwaretype']) && $params['hardwaretype'] != 0) {
				$hardwaretype = $params['hardwaretype'];
			} else {
				$hardwaretype = $hardware->hardwaretype;
			}
			
			if (isset($params['vendor']) && $params['vendor'] != 0) {
				$hardwareVendor = $params['vendor'];
			} else {
				$hardwareVendor = $hardware->vendor;
			}
			
			//check status valid of hardware
			if (isset($params['valid']) && $params['valid'] == 'on') {
				$valid = Sss_Ultility_Setting::HARDWARE_VALID;
			} else {
				$valid = Sss_Ultility_Setting::HARDWARE_INVALID;
			}
			//End
			//process add hardware
			$allocation = $stockLocationId == 0 ? Resources::_('NOT_ALLOCATED') : addslashes($allocation);
			$hardwareUpdate->setHardwareId($hardwareId);
			$hardwareUpdate->setHardwareName(addslashes($hardwareName));
			$hardwareUpdate->setVendor($hardwareVendor);
			$hardwareUpdate->setBuyer(addslashes($params['buyer']));
			$hardwareUpdate->setHardwaretype($hardwaretype);
			$hardwareUpdate->setStatus($params['status']);
			$hardwareUpdate->setAllocation($allocation);
			$hardwareUpdate->setPhoto($fullPath);
			$hardwareUpdate->setSoftVersion(addslashes($params['soft_version']));
			$hardwareUpdate->setHardVersion(addslashes($params['hard_version']));
			$hardwareUpdate->setUpdatedBy($createBy);
			$hardwareUpdate->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$hardwareUpdate->setOwner(addslashes($params['owner']));
			$hardwareUpdate->setNote(addslashes($params['note']));
			$hardwareUpdate->setValid($valid);
			$id = $hardwareTable->save($hardwareUpdate);
			return $id;
		}

		function deleteReference($hardwareId)
		{
			$referenceTable = new Application_Model_Mapper_References();
			$arrDeleteReference = array(
					'destination = ?' => $hardwareId,
					'referencetype = ?' => Sss_Ultility_Setting::DOCUMENT_HARDWARE);
			$referenceTable->deleteRow(null,$arrDeleteReference);
		}
		
		function saveEditHardware($hardwareId,$hardwareIds,$arrHardwareIds,$userInformation,$params,$stockLocation)
		{
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$stockLocationId = $stockLocation->stocklocationid;
			if ($hardwareId == '' && $hardwareIds != -1 && isset($hardwareIds)) {
				$totalCount = count($arrHardwareIds);
			}
			try {
				if ($hardwareId > 0 && $hardwareId != -1 && $hardwareId != '') {
					$totalCount = 1;
				}
				for ($i = 0; $i < $totalCount; $i++) {
					if (isset($arrHardwareIds) && count($arrHardwareIds) > 0 && $arrHardwareIds != '') {
						$hardwareId = $arrHardwareIds[$i];
					}
					if ($hardwareId > 0 && $hardwareId != -1 && $hardwareId != '') {
						$createBy = $userInformation['accountid'];
						//get hardware by id
						$hardware = $hardwareTable->getHardwareById($hardwareId, 1);
						if ($hardware == false) {
							$hardware = $hardwareTable->getHardwareById($hardwareId);
						}
						//process insert history
						self::processInsertHistory($params,$hardware,$createBy);
						//update hardware
						$Id = self::editHardware($hardwareId,$hardware,$params,$stockLocation,$createBy,$stockLocationId);
						if (isset($Id)) {
							self::deleteReference($hardwareId);
							//add document by hardware
							if ($params['documentid']) {
								$arrDocumentId = explode('_', $param['documentid']);
								self::addDocumentByHardware($arrDocumentId,$hardwareId);
							}
							//add inventory when add hardware successfull and delete if stocklocation is 0
							self::addInventoryEditHardware($stockLocationId,$hardware,$createBy,$hardwareId);
							if (isset($arrHardwareIds) && count($arrHardwareIds) > 0) {
								//add document by hardware
								$arrDocumentId = explode('_', $params['documentid']);
								self::addDocumentByHardware($arrDocumentId,$hardwareId);
							}
						}
					}
				}
				$message = Resources::_('EDIT_HARDWARES_SUCCESSFULL');
			} catch (Exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				$message = Resources::_('EDIT_HARDWARE_FAILED');
			}
			return $message;
		}
		function getStockLocationId($hardwareTable,$stockLocationTable,$stockLocationId,$hardware,$hardwareId,$hardwareIdDefault)
		{
			$stockLocation = $stockLocationTable->findById($stockLocationId);
			if ($stockLocationId == -1) {
				$stockLocation = false;
			}
			$hardwareDefault = null;
			if ($hardware != false) {
				if ($hardware->stocklocationid == null)
					$hardware = $hardwareTable->getHardwareById($hardwareId);
			} else if ($hardware == false) {
				$hardware = $hardwareTable->getHardwareById($hardwareId);
			} else {
				$hardware = null;
			}
			if ($hardwareId == '' || $hardwareIdDefault != '') {
				$hardware = null;
				$hardwareDefault = $hardwareTable->getHardwareById($hardwareIdDefault);
			}
			$arrValue['hardware'] = $hardware;
			$arrValue['hardwareDefault'] = $hardwareDefault;
			$arrValue['stocklocation'] = $stockLocation;
			return $arrValue;
		}
		function countTotalValid($hardwareTable,$hardwareIds)
		{
			$totalInvalid = 0;
			if ($hardwareIds != -1) {
				$arrHardwareIds = explode(',', $hardwareIds);
				//count total invalid
				foreach ($arrHardwareIds as $i) {
					$checkValid = $hardwareTable->getHardwareById($i);
					if ($checkValid->valid == Sss_Ultility_Setting::HARDWARE_INVALID) {
						$totalInvalid++;
					}
				}
				//End count
				$hardwareIdDefault = $arrHardwareIds[0];
			} else {
				$hardwareIdDefault = '';
			}
			$arrData['totalValid'] = $totalInvalid;
			$arrData['hardwareIdDefault'] = $hardwareIdDefault;
			return $arrData;
		}

		function setValueManyHardware($edit)
		{
			$arrValue = array();
			$arrEdits = explode(',', $edit);
			$arrValue['howner'] = $edit != -1 ? $arrEdits[0] : '';
			$arrValue['hvendor'] = $edit != -1 ? $arrEdits[1] : '';
			$arrValue['htype'] = $edit != -1 ? $arrEdits[2] : '';
			$arrValue['hlocation'] = $edit != -1 ? $arrEdits[3] : '';
			$arrValue['hstatus'] = $edit != -1 ? $arrEdits[4] : '';
			$arrValue['huser'] = $edit != -1 ? $arrEdits[5] : '';
			$arrValue['hsoft'] = $edit != -1 ? $arrEdits[6] : '';
			$arrValue['hhanrd'] = $edit != -1 ? $arrEdits[7] : '';
			return $arrValue;
		}
		
		function breadscrumbEditHardware($menuName)
		{
			$breadscrumbs = array(
					new Sss_CommonEntity_BreadScrumb($menuName, ''),
					new Sss_CommonEntity_BreadScrumb(Resources::_('HARDWARE'), '#'),
					new Sss_CommonEntity_BreadScrumb(Resources::_('EDIT_HARDWARE'), '#')
			);
			return $breadscrumbs;
		}
}